package com.gnerv.rabbitmq.agent.command.factory;

import com.gnerv.rabbitmq.agent.command.AbstractRabbitmqCommand;
import com.gnerv.rabbitmq.agent.model.entity.Node;
import com.google.common.collect.Maps;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author Gnerv LiGen
 */
@Data
public abstract class RabbitmqCommandFactory<T extends AbstractRabbitmqCommand> {

    private static Map<String, String> VERSION_MAPPING = Maps.newHashMap();

    static {
        VERSION_MAPPING.put("3.7.9", "v_3_7_x");
    }

    private String version;
    private Node node;
    public abstract String classPath();

    public T build() {
        String versionMapping = VERSION_MAPPING.get(version);
        if (StringUtils.hasText(versionMapping)) {
            Class<?> clazz = null;
            try {
                String className = String.format(classPath(), versionMapping);
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("创建处理器出错", e);
            }
            T rabbitmqCommand = null;
            try {
                rabbitmqCommand = (T) clazz.getDeclaredConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                     NoSuchMethodException e) {
                throw new RuntimeException("创建处理器出错", e);
            }
            return rabbitmqCommand;
        }
        throw new RuntimeException("没有版本信息");
    }

}
